package com.ltsznh.android.locationreporting;

import android.app.ActionBar;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.ltsznh.android.locationreporting.db.dbo;
import com.ltsznh.android.locationreporting.util.Tools;

import java.util.Date;

public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.


    private PolylineOptions polylineOptions;
    private Polyline polyline;
    private boolean isLocation = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        ActionBar actionBar = this.getActionBar();
        actionBar.setDisplayShowHomeEnabled(true);
//        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.show();

        setUpMapIfNeeded();

        mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                LrReceiver.report(location);
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
//                定位
                if (!isLocation) {
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
                    isLocation = true;
                }
                //画出最近路线。
                addHistory(latLng);
                if (polyline != null) polyline.remove();
                polyline = mMap.addPolyline(polylineOptions);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    @Override
    protected void onPause() {
        super.onPause();
        LrReceiver.init(this, this.getIntent());
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p/>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p/>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p/>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
//        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));

//        mMap.addMarker(new MarkerOptions().position(new LatLng(20, 20)).title("Marker2"));
//        mMap.clear();

        GoogleMapOptions mapOptions = new GoogleMapOptions();
        LrReceiver.removeUpdates();
        polylineOptions = new PolylineOptions().width(5).color(Color.BLUE);
        showHistory();

        mMap.setMyLocationEnabled(true);
        mMap.setBuildingsEnabled(true);
        mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
//        mMap.setIndoorEnabled(true);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_maps, menu);
        return true;
    }


    public void setting(MenuItem menuItem) {
        Intent intent = new Intent();
        intent.setClass(this, SettingActivity.class);
//        intent.putExtra("invDate","");
        startActivity(intent);
    }

    private void showHistory() {
        mMap.clear();
        Cursor cursor = dbo.rawQueryCursor(MapsActivity.this, "SELECT provider," +
                "       latitude," +
                "       longitude," +
                "       accuracy," +
                "       altitude," +
                "       bearing," +
                "       speed" +
                "  FROM lr_details" +
                " WHERE reportDate = ?" +
                " ORDER BY reportDatetime DESC;", new String[]{Tools.getDateFormat().format(new Date())});

        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            do {
                addHistory(cursor.getDouble(cursor.getColumnIndex("latitude")),
                        cursor.getDouble(cursor.getColumnIndex("longitude")));
            } while (cursor.moveToNext());
            cursor.close();
            if (polyline != null) polyline.remove();
            polyline = mMap.addPolyline(polylineOptions);
        }
    }

    public void addHistory(double latitude, double longitude) {
        LatLng latLng = new LatLng(latitude, longitude);
        addHistory(latLng);
    }

    private void addHistory(LatLng latLng) {
        polylineOptions.add(latLng);
        mMap.addMarker(new MarkerOptions().position(latLng).draggable(false).title("test"));
    }
}
